package com.atguigu.edu.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.edu.entity.Subject;
import com.atguigu.edu.excel.model.SubjectExcelData;
import com.atguigu.edu.service.SubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


public class SubjectExcelListener extends AnalysisEventListener<SubjectExcelData> {

    public SubjectService subjectService;

    public SubjectExcelListener() {}

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService =subjectService;
    }

    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
         if (subjectExcelData ==null) {
             throw new GuliException(20001,"数据为空");
         }

         Subject existOneSubject = this.existOneSubject(subjectService, subjectExcelData.getOneSubjectName());
         if (existOneSubject== null ) {
             existOneSubject = new Subject();
             existOneSubject.setTitle(subjectExcelData.getOneSubjectName());
             existOneSubject.setParentId("0");
             subjectService.save(existOneSubject);
         }

         String pid = existOneSubject.getId();

        Subject existTwoSubject = this.existTwoSubject(subjectService, subjectExcelData.getTwoSubjectName(),pid);
        if (existTwoSubject== null ) {
            existTwoSubject = new Subject();
            existTwoSubject.setTitle(subjectExcelData.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            subjectService.save(existTwoSubject);
        }



    }

    //判断一级分类不能重复
    private Subject existOneSubject(SubjectService subjectService,String title){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id","0");
        return subjectService.getOne(queryWrapper);
    }
    //判断二级分类不能重复
    private Subject existTwoSubject(SubjectService subjectService,String title,String pid){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",pid);
        return subjectService.getOne(queryWrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
